package com.ben.utils.ext

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.PixelFormat
import android.graphics.Rect
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager

/**
 * Author: bin.yang
 * Maintainer: bin.yang
 * Date: 2021/3/22
 * Copyright: 2021 Inc. All rights reserved.
 * Desc:
 */
fun Context.addWindowView(view: View, width: Int, height: Int, animStyleRes: Int = -1, needFocus: Boolean = true) {
    val params = WindowManager.LayoutParams()
    params.type = WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG
    params.format = PixelFormat.RGBA_8888
    params.flags = if (needFocus) WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
    else WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
    params.format = PixelFormat.TRANSLUCENT
    params.width = width
    params.height = height
    params.gravity = Gravity.CENTER
    if (animStyleRes != -1)
        params.windowAnimations = animStyleRes
    (applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).addView(view, params)
}

fun Context.removeWindowView(view: View) {
    tryCatch {
        (applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager).removeView(
            view
        )
    }
}

fun Dialog.resetWindow(width: Int, height: Int) {
    window?.also {
        it.setDimAmount(0.65f)
        if (context !is Activity) {
            it.setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG)
        }
        val wl = it.attributes
        wl.width = width
        wl.height = height
        onWindowAttributesChanged(wl)
    }
}

fun Window?.isKeyBoardShowing(): Boolean {
    val screenHeight = this?.decorView?.height ?: return false
    val rect = Rect()
    this.decorView.getWindowVisibleDisplayFrame(rect)
    return screenHeight * 2 / 3 > rect.bottom
}
